package com.open.capacity.finance.controller;

import com.open.capacity.commons.Result;
import com.open.capacity.finance.entity.SpringScheduledCron;
import com.open.capacity.finance.service.SpringScheduledCronService;
import com.open.capacity.finance.task.ScheduledOfTask;
import com.open.capacity.utils.DateUtil;
import com.open.capacity.vo.TreeVo;
import io.swagger.annotations.Api;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.*;


/**
 * 手工触发定时任务
 *
 * @author
 * @email
 * @date 2020-06-03 22:56:51
 */
@RestController
@RequestMapping("scheduleManuals")
@Api(tags = "系统属性")
public class ScheduleManualController {

    @Autowired
    private ApplicationContext context;

    @Autowired
    private SpringScheduledCronService cronService;

    /**
     * 手工触发
     */
    @RequestMapping("/trigger")
    public Result trigger(Integer cronId, String startTime) {
        SpringScheduledCron cron = cronService.findById(cronId);
        Class<?> clazz;
        Object task;
        try {
            clazz = Class.forName(cron.getCronKey());
            task = context.getBean(clazz);
        } catch (ClassNotFoundException e) {
            throw new IllegalArgumentException("spring_scheduled_cron表数据" + cron.getCronKey() + "有误", e);
        } catch (BeansException e) {
            throw new IllegalArgumentException(cron.getCronKey() + "未纳入到spring管理", e);
        }
        try {
            ((ScheduledOfTask) task).trigger(startTime);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return Result.succeed("同步成功");
    }
}
